package com.yuanfud.user.service.impl;

import com.yuanfud.common.encrypt.MD5Util;
import com.yuanfud.common.exception.RestException;
import com.yuanfud.common.util.ErrorCode;
import com.yuanfud.common.util.JwtHandler;
import com.yuanfud.entity.user.Token;
import com.yuanfud.entity.user.User;
import com.yuanfud.user.mapper.UserMapper;
import com.yuanfud.user.service.LoginService;
import org.jose4j.lang.JoseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User Login(User user) throws RestException {
        user.setPwd(MD5Util.MD5Encrypt(MD5Util.MD5Encrypt(user.getPwd())+"yuanfud"));
        System.out.println(user.toString());
        User userInfo=userMapper.Login(user);

        return userInfo;
    }

    @Override
    public Token getJwtToken(User user, String ip) throws RestException {
        User userInfo=Login(user);
        if(userInfo==null)
            throw new RestException(ErrorCode.LOGIN_ERROR,ErrorCode.LOGIN_ERROR_MSG);

        Map<String,Object> tokenMap = new LinkedHashMap<>();

        HashMap accountMap = new HashMap();

        accountMap.put("Id",userInfo.getId());
        accountMap.put("userName",userInfo.getUserName());
        accountMap.put("loginId",userInfo.getLoginID());
        try
        {
            tokenMap = JwtHandler.getJwtToken(accountMap,ip);
        } catch (JoseException e)
        {
            throw  new RestException(ErrorCode.LOGIN_TOKEN_CREATE_ERROR,ErrorCode.LOGIN_TOKEN_CREATE_ERROR_MSG);
        }

        Token token = new Token();
        token.setAppkey((String)tokenMap.get("appKey"));
        token.setToken((String)tokenMap.get("idToken"));
        token.setUserName(userInfo.getUserName());
        token.setLoginId(userInfo.getLoginID());
        token.setUserId((Integer)tokenMap.get("Id"));
        return token;
    }
}
